# After inporting rips from RMG-Portable v0.2.4 and GLideN64-SceneRipper plugin using GLR Importer addon for Blender 
# You'll find you can't save .dae models from the rip with textures pathing intact. 
# This script will convert Shader based nodes to Texture base nodes.
#
# Load this script and selct the object you want to convert to use Texture base node (Principled BSDF) Than run the script.
# Now select the object you want to export. Set the .dae export options to "Selection Only" and Use the Texture Options of "Copy". 
# This will save the dae with all texure that the selected model uses in the same location.
#
# This will also let you save .obj/mtl as well but you will lose the vertex coloring. May also work for other export types.
#
import bpy

def make_material_collada_compatible(mat, image=None):
    """Convert a material to COLLADA-compatible Principled BSDF with optional image texture"""
    
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links

    # Clear existing nodes
    nodes.clear()

    # Create Material Output
    output_node = nodes.new(type='ShaderNodeOutputMaterial')
    output_node.location = (400, 0)

    # Create Principled BSDF
    principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
    principled_node.location = (0, 0)

    links.new(principled_node.outputs['BSDF'], output_node.inputs['Surface'])

    # Add Image Texture if it exists
    if image:
        tex_node = nodes.new(type='ShaderNodeTexImage')
        tex_node.image = image
        tex_node.location = (-300, 0)
        # Blender 4.0 correct way to set color space
        tex_node.image.colorspace_settings.name = 'sRGB'
        links.new(tex_node.outputs['Color'], principled_node.inputs['Base Color'])
    else:
        # Default base color for materials without texture
        principled_node.inputs['Base Color'].default_value = (0.8, 0.8, 0.8, 1)

# Loop over all materials
for mat in bpy.data.materials:
    img = None
    if mat.use_nodes:
        for node in mat.node_tree.nodes:
            if node.type == 'TEX_IMAGE' and node.image is not None:
                img = node.image
                break
    make_material_collada_compatible(mat, image=img)

print("All materials converted to COLLADA-compatible Principled BSDFs.")
